﻿Imports System.Security.Cryptography
Imports System.Text

Public Class ctrUsuario
    Inherits ctrPadrao

#Region "Declaração de variáveis"
    Private objSeguranca As New Persistencia.perSeguranca
    Private objUsuario As New Persistencia.perUsuario
    Private objUsuariosSetores As New Persistencia.perUsuariosSetores
    Private iIdUsuario As Int32

#End Region

#Region "Criptografia"

    Private Shared TripleDES As New TripleDESCryptoServiceProvider
    Private Shared MD5 As New MD5CryptoServiceProvider
    ' Definição da chave de encriptação/desencriptação 
    Private Const key As String = "CHAVE12345teste"

    ''' <summary> 
    ''' Calcula o MD5 Hash  
    ''' </summary> 
    ''' <param name="value">Chave</param> 
    Public Shared Function MD5Hash(ByVal value As String) As Byte()
        ' Converte a chave para um array de bytes  
        Dim byteArray() As Byte = ASCIIEncoding.ASCII.GetBytes(value)
        Return MD5.ComputeHash(byteArray)
    End Function

    ''' <summary> 
    ''' Encripta uma string com base em uma chave 
    ''' </summary> 
    ''' <param name="sSenha">String a encriptar</param> 
    Public Function encriptarSenha(ByVal sSenha As String) As String

        Try
            ' Definição da chave e da cifra (que neste caso é Electronic 
            ' Codebook, ou seja, encriptação individual para cada bloco) 
            TripleDES.Key = MD5Hash(key)
            TripleDES.Mode = CipherMode.ECB
            ' Converte a string para bytes e encripta 
            Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(sSenha)
            Return Convert.ToBase64String(TripleDES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            Throw New Exception("Ocorreu um erro no método 'encriptarSenha'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Function

    ''' <summary> 
    ''' Desencripta uma string com base em uma chave 
    ''' </summary> 
    ''' <param name="sSenha">String a decriptar</param> 
    Public Function desencriptarSenha(ByVal sSenha As String) As String

        Try
            ' Definição da chave e da cifra 
            TripleDES.Key = MD5Hash(key)
            TripleDES.Mode = CipherMode.ECB
            ' Converte a string encriptada para bytes e decripta 
            Dim Buffer As Byte() = Convert.FromBase64String(sSenha)
            Return ASCIIEncoding.ASCII.GetString(TripleDES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            Throw New Exception("Ocorreu um erro no método 'desencriptarSenha'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Function

#End Region

#Region "Propriedades"

    Public Property IDUsuario() As Int32
        Get
            Return Me.iIdUsuario
        End Get
        Set(ByVal value As Int32)
            Me.iIdUsuario = value
        End Set
    End Property

    Public ReadOnly Property sqlConsulta() As String
        Get
            Return Me.objUsuario.sqlConsulta
        End Get
    End Property

#End Region

#Region "Métodos públicos"

    Public Function salvar(ByVal iIdUsuario As Int32, _
                           ByVal sNome As String, _
                           ByVal sLogin As String, _
                           ByVal sSenha As String, _
                           ByVal iIDGrupoAcesso As Int32, _
                           ByVal dsSetores As DataSet) As Boolean

        Dim bResultado As Boolean = False
        Dim sLoginEncriptado As String
        Dim sSenhaEncriptada As String
        Dim sLoginFormatado As String

        sLoginFormatado = sLogin.Replace(" ", "")
        sLoginEncriptado = Me.encriptarSenha(sLoginFormatado)
        sSenhaEncriptada = Me.encriptarSenha(sSenha)

        If iIdUsuario > 0 Then
            Me.alterarUsuario(iIdUsuario, _
                              sNome, _
                              sLoginEncriptado, _
                              sSenhaEncriptada, _
                              iIDGrupoAcesso, _
                              dsSetores)
            Me.iIdUsuario = iIdUsuario
            bResultado = True
        Else
            Me.iIdUsuario = Me.inserirUsuario(sNome, _
                                              sLoginEncriptado, _
                                              sSenhaEncriptada, _
                                              iIDGrupoAcesso, _
                                              dsSetores)

            bResultado = True
        End If

        Return bResultado

    End Function

    Public Function excluir(ByVal iIdUsuario As Int32) As Boolean
        Dim bResultado As Boolean = True

        If bResultado Then
            Me.excluirUsuario(iIdUsuario)
        End If

        Return bResultado

    End Function

    Private Sub excluirUsuario(ByVal iIdUsuario As Int32)

        Try
            Me.objUsuario.excluirUsuario(iIdUsuario)
        Catch ex As Exception
            Throw New Exception("Exceção no método 'excluirUsuario'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Sub

    Public Function selecionarUsuario(ByVal iIdUsuario As Int32) As DataRow
        Try
            Return Me.objUsuario.selecionarUsuario(iIdUsuario)
        Catch ex As Exception
            Throw New Exception("Exceção no método 'selecionarUsuario'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try
    End Function

    Public Function retornarCampoUsuario(ByVal sCampo As String, _
                                         ByVal iIdUsuario As Int32) As DataRow

        Try
            Dim dtDados As New DataTable

            dtDados = Me.objUsuario.selecionarCampoUsuario(sCampo, _
                                                           iIdUsuario)

            If Not dtDados Is Nothing Then
                Return dtDados.Rows(0)
            Else
                Return Nothing
            End If
        Catch ex As Exception
            Throw New Exception("Exceção no método 'retornarCampoUsuario'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Function
    Public Function VerificaLogin(ByVal sLogin As String, ByVal sSenha As String) As Int32
        Dim dtUsuario As DataTable
        Dim validacaoUsuario As Int32
        Try
            dtUsuario = objUsuario.verificarUsuario(objSeguranca.criptografar(sLogin))
            With dtUsuario
                If (.Rows.Count > 0) Then
                    If (.Rows(0).Item("Senha").ToString = objSeguranca.criptografar(sSenha)) Then
                        validacaoUsuario = CInt(.Rows(0).Item("IDUsuario").ToString)
                    Else
                        MsgBox("Senha incorreta.", MsgBoxStyle.Exclamation, "Login")
                        validacaoUsuario = -1
                    End If
                Else
                    MsgBox("Usuário não cadastrado", MsgBoxStyle.Exclamation, "Login")
                    validacaoUsuario = -1
                End If
            End With

        Catch ex As Exception
            Throw New Exception("Exceção no método 'VerificaLogin'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

        VerificaLogin = validacaoUsuario
    End Function

#End Region

#Region "Métodos privados"

    Private Sub alterarUsuario(ByVal iIdUsuario As Int32, _
                               ByVal sNome As String, _
                               ByVal sLogin As String, _
                               ByVal sSenha As String, _
                               ByVal iIDGrupoAcesso As Int32, _
                               ByVal dsSetores As DataSet)

        Dim dtUsuariosSetores As DataTable

        Try

            Me.objUsuario.alterarUsuario(iIdUsuario, _
                                         sNome, _
                                         sLogin, _
                                         sSenha, _
                                         iIDGrupoAcesso)

            dtUsuariosSetores = Me.objUsuariosSetores.selecionarUsuariosSetores(0, 0)

            If Not dsSetores Is Nothing AndAlso dsSetores.Tables("DC_UsuariosSetores").Rows.Count > 0 Then
                For Each drDados As DataRow In dsSetores.Tables("DC_UsuariosSetores").Rows
                    If Persistencia.perConversao.ToBoolean(drDados.Item("Marcar")) Then
                        If Not dtUsuariosSetores Is Nothing AndAlso dtUsuariosSetores.Select("IdUsuario= " & iIdUsuario & " AND " & _
                                                                                             "IdSetor= " & drDados.Item("IDSetor")).Length > 0 Then
                            Me.objUsuariosSetores.alterarUsuariosSetores(Persistencia.perConversao.ToInt32(drDados.Item("IDSetor")), _
                                                                         iIdUsuario)
                        Else
                            Me.objUsuariosSetores.inserirUsuariosSetores(iIdUsuario, _
                                                                         Persistencia.perConversao.ToInt32(drDados.Item("IDSetor")))
                        End If
                    End If
                Next
            End If

            If Not dtUsuariosSetores Is Nothing Then
                For Each drDados As DataRow In dtUsuariosSetores.Rows
                    If dsSetores.Tables("DC_UsuariosSetores").Select("IdUsuario= " & iIdUsuario & " AND " & _
                                                                     "IdSetor= " & drDados.Item("IDSetor")).Length <= 0 Then
                        Me.objUsuariosSetores.excluirUsuariosSetores(Persistencia.perConversao.ToInt32(drDados.Item("IDSetor")), _
                                                                     iIdUsuario)
                    End If
                Next
            End If

        Catch ex As Exception
            Throw New Exception("Exceção no método 'alterarUsuario'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Sub

    Private Function inserirUsuario(ByVal sNome As String, _
                                    ByVal sLogin As String, _
                                    ByVal sSenha As String, _
                                    ByVal iIDGrupoAcesso As Int32, _
                                    ByVal dsSetores As DataSet)

        Dim iIdUsuario As Int32

        Try
            iIdUsuario = Me.objUsuario.inserirUsuario(sNome, _
                                                      sLogin, _
                                                      sSenha, _
                                                      iIDGrupoAcesso)

            If Not dsSetores Is Nothing AndAlso dsSetores.Tables("DC_UsuariosSetores").Rows.Count > 0 Then
                For Each drDados As DataRow In dsSetores.Tables("DC_UsuariosSetores").Rows
                    Me.objUsuariosSetores.inserirUsuariosSetores(iIdUsuario, _
                                                                 Persistencia.perConversao.ToInt32(drDados.Item("IDSetor")))
                Next
            End If

            Return iIdUsuario

        Catch ex As Exception
            Throw New Exception("Exceção no método 'inserirUsuario'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Function

#End Region
End Class
